package com.atguitu.campus.renwendemo.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguitu.campus.renwendemo.utils.HttpUtils;
import com.atguitu.campus.renwendemo.utils.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SparkService {


    public String sendMessage(String role,String question) throws MyException {
        String res = "";
        try {
            // POST JSON 请求示例
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("model","lite");
            jsonBody.put("user","user_1234567876");
            JSONArray messageArr = new JSONArray();
            JSONObject message = new JSONObject();
            message.put("role","system");
            message.put("content",role);
            JSONObject user = new JSONObject();
            messageArr.add(message);
            user.put("role","user");
            user.put("content",question);
            messageArr.add(user);


            jsonBody.put("messages",messageArr);

            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization","Bearer elumSDRdJlnLalmRlxnK:dpRJBCFVdTBnBKJKeGIz");
            headers.put("Content-Type","application/json");
            String postResponse = HttpUtils.postJson("https://spark-api-open.xf-yun.com/v1/chat/completions", jsonBody.toJSONString(),headers);
            System.out.println("POST Response: " + postResponse);
            JSONObject resJson = JSONObject.parseObject(postResponse);
            JSONArray choices = resJson.getJSONArray("choices");
            res = choices.getJSONObject(0).getJSONObject("message").getString("content");

        } catch (IOException e) {
            log.error("大模型调用失败：{}",e);
            throw new MyException("大模型调用失败");
        }
        return res;
    }
}
